#!/bin/bash

# 学生选课系统部署脚本
# 服务器部署自动化脚本

set -e

echo "🚀 开始部署学生选课系统..."

# 服务器信息
SERVER_IP="166.88.182.218"
SERVER_USER="root"
SERVER_PASSWORD="G4QiH1cM3qAh6P5"
PROJECT_NAME="student-course-system"
DEPLOY_PATH="/opt/${PROJECT_NAME}"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印彩色消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查本地环境
check_local_env() {
    print_message "检查本地环境..."
    
    # 检查 Docker
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    # 检查 sshpass
    if ! command -v sshpass &> /dev/null; then
        print_warning "sshpass 未安装，将使用手动密码输入"
    fi
    
    print_message "本地环境检查完成"
}

# 构建项目
build_project() {
    print_message "构建项目..."
    
    # 构建前端
    cd client
    npm install
    npm run build
    cd ..
    
    # 创建部署包
    mkdir -p deploy-package
    
    # 复制必要文件
    cp -r src deploy-package/
    cp -r client/dist deploy-package/client/
    cp package*.json deploy-package/
    cp database.sqlite deploy-package/
    cp Dockerfile.prod deploy-package/
    cp docker-compose.prod.yml deploy-package/
    cp nginx.conf deploy-package/
    cp .env.example deploy-package/.env
    
    # 创建部署包
    tar -czf ${PROJECT_NAME}.tar.gz deploy-package/
    
    print_message "项目构建完成"
}

# 上传到服务器
upload_to_server() {
    print_message "上传项目到服务器..."
    
    # 使用 scp 上传
    if command -v sshpass &> /dev/null; then
        sshpass -p "${SERVER_PASSWORD}" scp -o StrictHostKeyChecking=no ${PROJECT_NAME}.tar.gz ${SERVER_USER}@${SERVER_IP}:/tmp/
    else
        echo "请输入服务器密码："
        scp ${PROJECT_NAME}.tar.gz ${SERVER_USER}@${SERVER_IP}:/tmp/
    fi
    
    print_message "项目上传完成"
}

# 在服务器上部署
deploy_on_server() {
    print_message "在服务器上部署..."
    
    # SSH 执行部署命令
    if command -v sshpass &> /dev/null; then
        sshpass -p "${SERVER_PASSWORD}" ssh -o StrictHostKeyChecking=no ${SERVER_USER}@${SERVER_IP} << 'EOF'
#!/bin/bash

PROJECT_NAME="student-course-system"
DEPLOY_PATH="/opt/${PROJECT_NAME}"

echo "🔄 开始服务器端部署..."

# 安装 Docker (如果未安装)
if ! command -v docker &> /dev/null; then
    echo "安装 Docker..."
    curl -fsSL https://get.docker.com | sh
    systemctl enable docker
    systemctl start docker
fi

# 安装 Docker Compose (如果未安装)
if ! command -v docker-compose &> /dev/null; then
    echo "安装 Docker Compose..."
    curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi

# 创建部署目录
mkdir -p ${DEPLOY_PATH}
cd ${DEPLOY_PATH}

# 停止旧服务
if [ -f docker-compose.prod.yml ]; then
    echo "停止旧服务..."
    docker-compose -f docker-compose.prod.yml down
fi

# 解压新项目
tar -xzf /tmp/${PROJECT_NAME}.tar.gz --strip-components=1

# 创建必要目录
mkdir -p data logs

# 设置权限
chown -R root:root .
chmod +x deploy.sh

# 启动服务
echo "启动新服务..."
docker-compose -f docker-compose.prod.yml up --build -d

# 等待服务启动
sleep 30

# 检查服务状态
echo "检查服务状态..."
docker-compose -f docker-compose.prod.yml ps

# 清理临时文件
rm -f /tmp/${PROJECT_NAME}.tar.gz

echo "✅ 服务器端部署完成！"
EOF
    else
        echo "请输入服务器密码，然后手动执行以下命令："
        echo "ssh ${SERVER_USER}@${SERVER_IP}"
        echo "然后在服务器上运行部署命令..."
    fi
    
    print_message "服务器部署完成"
}

# 验证部署
verify_deployment() {
    print_message "验证部署..."
    
    # 等待服务启动
    sleep 10
    
    # 检查服务是否可访问
    if curl -f http://${SERVER_IP}/health > /dev/null 2>&1; then
        print_message "✅ 部署成功！服务已正常运行"
        print_message "🌐 访问地址: http://${SERVER_IP}"
        print_message "👤 管理员账号: admin / admin123"
        print_message "👨‍🏫 教师账号: teacher1 / teacher123"
        print_message "🎓 学生账号: student1 / student123"
    else
        print_warning "⚠️  服务可能还在启动中，请稍后检查: http://${SERVER_IP}"
    fi
}

# 清理临时文件
cleanup() {
    print_message "清理临时文件..."
    rm -rf deploy-package
    rm -f ${PROJECT_NAME}.tar.gz
    print_message "清理完成"
}

# 主要部署流程
main() {
    print_message "🎯 学生选课系统自动部署开始"
    print_message "📍 目标服务器: ${SERVER_IP}"
    
    check_local_env
    build_project
    upload_to_server
    deploy_on_server
    verify_deployment
    cleanup
    
    print_message "🎉 部署流程完成！"
}

# 执行主流程
main "$@" 